import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author wangj881
 * @date 2024-12-13 17:48
 */
public class L39_2 {

    public static void main(String[] args) {
        int[] candidates = {2, 3, 6, 7};
        int target = 7;
        List<List<Integer>> lists = new Solution().combinationSum(candidates, target);
        for (List<Integer> list : lists) {
            System.out.println(list.toString());
        }

    }

    static class Solution {
        ArrayList<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> list = new LinkedList<>();

        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            backTracing(candidates, target, 0);
            return result;
        }

        private void backTracing(int[] candidates, int target, int index) {
            if (target < 0) {
                return;
            }
            if (target == 0) {
                result.add(new ArrayList<>(list));
                return;
            }
            for (int i = index; i < candidates.length; i++) {
                target -= candidates[i];
                list.addLast(candidates[i]);
                backTracing(candidates, target, i);
                target += candidates[i];
                list.removeLast();

            }
        }
    }
}
